﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;


using PowerCreator.LMS.DL.Project.Entity;
using PowerCreator.LMS.Web.DL.Project;
using PowerCreator.LMS.Common.Script;

public partial class sysadmin_DL_Project_StudentRank : PowerCreator.LMS.Web.Base.WebBasePage
{
    protected string ClassName = string.Empty;
    protected string ClassUserNum = string.Empty;
    PowerCreator.LMS.ViewQuery.ViewQuery obj = new PowerCreator.LMS.ViewQuery.ViewQuery();
    VOTOClass voClass = new VOTOClass();
    TOClass objClass = new TOClass();
    TOUserOfClass objClassUser = new TOUserOfClass();
   
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            InitPage();
            int CID = 0;
            if (Request.QueryString["CID"] != null)
            {
                CID = int.Parse(Request.QueryString["CID"].ToString());
                ViewState["CID"] = CID.ToString();
                voClass = objClass.Load(CID);
                ClassName = voClass.Name;
                string search = GetSearch(CID);
                BinderPG(search);
            }
        }
    }



    protected override void InitPage()
    {
        btnSearch.Text = GetLanageValueByKey("btn_Search", PowerCreator.LMS.Language.LanagetItemType.Page);

        base.InitPage();
    }
    private string GetSearch(int cid)
    {
        string search = "SELECT TO_UserOfClass.UOC_ID, TO_UserOfClass.UserID,  TO_Learner.UserName, TO_Learner.TeacherId, TO_Learner.Name,  TO_Learner.UserGroup, TO_Learner.UserPIC, TO_Learner.Mobile,  TO_Learner.Email, TO_Learner.ZhiCheng, TO_Learner.ZhiWu,  TO_Learner.Education,TO_UserOfClass.IsCourseFDY FROM TO_Learner ,TO_UserOfClass where TO_Learner.Learner_Id = TO_UserOfClass.UserID  and TO_UserOfClass.ClassID=" + cid;
        if (!string.IsNullOrEmpty(txt_KeyWord.Text))
            search += string.Format(" and ( TO_Learner.Name like '%{0}%' or  TO_Learner.UserName like '%{0}%')", txt_KeyWord.Text.Trim());
        return search;
    }


    private void BinderPG(string search)
    {
        DataTable dtStu = obj.Query(search);
        ClassUserNum = dtStu.Rows.Count.ToString();
        Session["ClassUserNum"] = ClassUserNum.ToString();
        //开始计算分数和排名
        double intscoresStuCou = 0;
        double intscoresStu = 0;
        double douScoreP = 0;
        string strClassSearch = "SELECT TO_Class.Class_Id,TO_Class.Name,  TO_CourseList.CourseListName, TO_Class.Broswer, TO_Class.ClassAssistant, TO_Class.ClassLeader, TO_Class.ClassLecturer,TO_CourseList.CourseID FROM TO_Class ,TO_CourseList Where TO_Class.ClassCourseListID = TO_CourseList.CourseList_Id and TO_Class.Class_Id =" + ViewState["CID"].ToString();
        DataTable dt = obj.Query(strClassSearch);//得到班级信息
        PowerCreator.LMS.ViewQuery.ViewQuery objView = new PowerCreator.LMS.ViewQuery.ViewQuery();
        string searchView = "";
        if (dt.Rows.Count == 0)
        {
            return;
        }
            string strClsCourseID = dt.Rows[0]["CourseID"].ToString();
            string[] strCourseIDA = strClsCourseID.Split(',');
            //得到班级批次
            string searchBatch = "select a.Batch_Id,Batch from TO_Batch as a ,TO_CourseList as b ,to_class as c where a.Batch_Id =b.Batch_Id and b.CourseList_Id = c.ClassCourseListID and c.Class_Id={0}";
            DataTable dtBatch = objView.Query(string.Format(searchBatch, ViewState["CID"].ToString()));
            string strBatch = dtBatch.Rows[0]["Batch"].ToString();
            string strBatchID = dtBatch.Rows[0]["Batch_Id"].ToString();
            //得到每个班的学员
            string searchUser = "SELECT TO_UserOfClass.UserID,TO_UserOfClass.UOC_ID,TO_Learner.UserName, TO_Learner.TeacherId, TO_Learner.Name, TO_Learner.UserGroup, TO_Learner.UserPIC, TO_Learner.Mobile,  TO_Learner.Email, TO_Learner.ZhiCheng, TO_Learner.ZhiWu, TO_Learner.Education FROM TO_Learner ,TO_UserOfClass where TO_Learner.Learner_Id = TO_UserOfClass.UserID and TO_UserOfClass.ClassID=" + ViewState["CID"].ToString();
            
            DataTable dtUser = objView.Query(searchUser);
            dtUser.Columns.Add("colScoreStu",typeof(float));//学员得分
            dtUser.Columns.Add("levelStu");//学员名次
            for (int m = 0; m < dtUser.Rows.Count; m++)
             {
                for (int n = 0; n < strCourseIDA.Length; n++)
                {
                    //截取课程id 和 学分 ,0为课程ID，1为学分
                    string[] strCourseIDB = strCourseIDA[n].Split('#');
                    string seacherInfoA = "select * from to_course where course_Id=" + strCourseIDB[0];
                    DataTable dtCourseInfo = objView.Query(seacherInfoA);
                    //得到每个学员每门课的总学时 
                    string searchCourse = "select sum(SscrlogTotalTime) as studyHours,FKSscrlogCourseID from TStudentStudyCouReslog group by FKSscrlogUserID,FKSscrlogTrainclaID,FKSscrlogCourseID having FKSscrlogUserID={0} and FKSscrlogTrainclaID={1} and FKSscrlogCourseID ={2}";
                    searchView = string.Format(searchCourse, dtUser.Rows[n]["UserID"].ToString(), ViewState["CID"].ToString(), strCourseIDB[0]);
                    DataTable dtCourse = objView.Query(searchView);
                    //得到作业完成次数
                    string searchWorkNum = "select count(*) as WorkNum,courseID,Creator ,ClassID from (select courseID,a.Creator,ClassID from TO_UserClassTask as a ,TO_ClassTasks as b where a.task_Id =b.ClassTasks_Id) as tb group by courseID,Creator ,ClassID having Creator ={0} and classID ={1} and courseID ={2}";
                    searchView = string.Format(searchWorkNum, dtUser.Rows[n]["UserID"].ToString(), ViewState["CID"].ToString(), strCourseIDB[0]);
                    DataTable dtWorkNum = objView.Query(searchView);
                    //得到作业评论次数
                    string searchTasksReply = "select count(*) as ReplyNum ,Creator,ClassID,courseID from (select courseID,b.Creator,ClassID from TO_ClassTasksReply as a ,TO_UserClassTask as b ,TO_ClassTasks as c  where a.UserTask_Id = b.UserTask_Id and b.task_Id = c.ClassTasks_Id ) as tb group by Creator,ClassID,courseID having Creator ={0} and classID ={1} and courseID ={2}";
                    searchView = string.Format(searchTasksReply, dtUser.Rows[n]["UserID"].ToString(), ViewState["CID"].ToString(), strCourseIDB[0]);
                    DataTable dtTasksReply = objView.Query(searchView);

                    //string strCourseID = dtCourse.Rows[0]["FKSscrlogCourseID"];
                    //得到考试成绩
                    string searchExam = "select * from UserPaperHistory where fKUPHistoryClassID={0} and fKUPHistoryUserID ={1} and fKUPHistoryCourseID={2}";
                    searchView = string.Format(searchExam, ViewState["CID"].ToString(), dtUser.Rows[n]["UserID"].ToString(), strCourseIDB[0]);
                    DataTable dtExam = objView.Query(searchView);
                    //得到规则
                    string searchRuleList = "select top 1 isnull(TotalTime_Low,0) as TotalTime_Low,isnull(TotalTime_High,0) as TotalTime_High,	isnull(TotalTimeWeightA,0) as TotalTimeWeightA,isnull(WorkFinishTimes_Low,0) as WorkFinishTimes_Low,isnull(WorkFinishTimes_High,0) as WorkFinishTimes_High,isnull(WorkFinishTimesWeightB,0) as WorkFinishTimesWeightB,isnull(WorkCommentTimes_Low,0) as WorkCommentTimes_Low,isnull(WorkCommentTimes_High,0) as WorkCommentTimes_High,isnull(WorkCommentTimesWeightB,0) as WorkCommentTimesWeightB,isnull(WorkTatolWeigthA,0) as WorkTatolWeigthA,isnull(Score_Low,0) as Score_Low,isnull(Score_High,0) as	Score_High,isnull(ScoreWeightA,0) as ScoreWeightA from TO_FormulaOfRule as a,to_rule as b where b.Rule_ID = a.RuleID and FKBatchID ={0} and FKCourseID={1}";
                    searchView = string.Format(searchRuleList, strBatchID, strCourseIDB[0]);
                    DataTable dtRuleList = objView.Query(searchView);
                    //计算平均成绩使用的变量
                    double intHours = 0;
                    double intTotalTimeWeightA = 0;
                    double TotalTime_Low = 0;
                    double TotalTime_High = 0;
                    double intScoresHours = 0;

                    double intworkFinishTimes = 0;
                    double intFinishTimesWeightB = 0;
                    double WorkFinishTimes_Low = 0;
                    double intWorkScores = 0;
                    double WorkFinishTimes_High = 0;


                    double intTasksReply = 0;
                    double workCommentTimesWeightB = 0;
                    double WorkCommentTimes_Low = 0;
                    double WorkCommentTimes_High = 0;
                    double intScoresComment = 0;

                    double intworkTatolWeightA = 0;
                    double intExam = 0;
                    double intScoreWeightA = 0;
                    double Score_Low = 0;
                    double Score_High = 0;
                    double intScoresExam = 0;

                    //如果没有设置，那么不去计算
                    if (dtCourse.Rows.Count > 0 && dtRuleList.Rows.Count > 0 )
                    {
                        //计算每个学员每门课的学分
                        intHours = int.Parse(dtCourse.Rows[n]["studyHours"].ToString());
                        intTotalTimeWeightA = int.Parse(dtRuleList.Rows[0]["TotalTimeWeightA"].ToString());
                        TotalTime_Low = double.Parse(dtRuleList.Rows[0]["TotalTime_Low"].ToString())*3600;
                        TotalTime_High = double.Parse(dtRuleList.Rows[0]["TotalTime_High"].ToString())*3600;
                        intScoresHours = 0;

                        if (intHours < TotalTime_High && intHours > TotalTime_Low && TotalTime_High>0)
                        {
                            intScoresHours = intHours / TotalTime_High;// intTotalTimeWeightA / 100;
                        }
                        else if (intHours >= TotalTime_High && TotalTime_High > 0)
                        {
                            intScoresHours = 1;
                        }
                        else
                        {
                            intScoresHours = 0;
                        }
                    }
                    if (dtWorkNum.Rows.Count > 0 && dtRuleList.Rows.Count > 0)
                    {
                        //计算作业完成次数得分
                        intworkFinishTimes = int.Parse(dtWorkNum.Rows[n]["WorkNum"].ToString());
                        intFinishTimesWeightB = int.Parse(dtRuleList.Rows[0]["WorkFinishTimesWeightB"].ToString());
                        WorkFinishTimes_Low = int.Parse(dtRuleList.Rows[0]["WorkFinishTimes_Low"].ToString());
                        intWorkScores = 0;
                        WorkFinishTimes_High = int.Parse(dtRuleList.Rows[0]["WorkFinishTimes_High"].ToString());

                        if (intworkFinishTimes < WorkFinishTimes_High && intworkFinishTimes > WorkFinishTimes_Low && WorkFinishTimes_High>0)
                        {
                            intWorkScores = intworkFinishTimes / WorkFinishTimes_High;// intFinishTimesWeightB / 100;
                        }
                        else if (intworkFinishTimes >= WorkFinishTimes_High && WorkFinishTimes_High > 0)
                        {
                            intWorkScores = 1;
                        }
                        else
                        {
                            intWorkScores = 0;
                        }
                    }
                    if (dtTasksReply.Rows.Count > 0 && dtRuleList.Rows.Count > 0)
                    {
                        //计算作业提交次数得分
                        intTasksReply = int.Parse(dtTasksReply.Rows[n]["ReplyNum"].ToString());
                        workCommentTimesWeightB = int.Parse(dtRuleList.Rows[0]["workCommentTimesWeightB"].ToString());
                        WorkCommentTimes_Low = int.Parse(dtRuleList.Rows[0]["WorkCommentTimes_Low"].ToString());
                        WorkCommentTimes_High = int.Parse(dtRuleList.Rows[0]["WorkCommentTimes_High"].ToString());
                        intScoresComment = 0;

                        if (intTasksReply < WorkCommentTimes_High && intTasksReply > WorkCommentTimes_Low && WorkCommentTimes_High>0)
                        {
                            intScoresComment = intTasksReply / WorkCommentTimes_High; //workCommentTimesWeightB / 100;
                        }
                        else if (intTasksReply >= WorkCommentTimes_High && WorkCommentTimes_High > 0)
                        {
                            intScoresComment = 1;
                        }
                        else
                        {
                            intScoresComment = 0;
                        }
                    }


                    if (dtExam.Rows.Count > 0 && dtRuleList.Rows.Count > 0)
                    {
                        //计算考试成绩得分
                        intworkTatolWeightA = int.Parse(dtRuleList.Rows[0]["WorkTatolWeigthA"].ToString());
                        intExam = int.Parse(dtExam.Rows[n]["UPHistoryScore"].ToString());
                        intScoreWeightA = int.Parse(dtRuleList.Rows[0]["ScoreWeightA"].ToString());
                        Score_Low = int.Parse(dtRuleList.Rows[0]["Score_Low"].ToString());
                        Score_High = int.Parse(dtRuleList.Rows[0]["Score_High"].ToString());
                        intScoresExam = 0;

                        if (intExam < Score_High && intExam > Score_Low && Score_High>0)
                        {
                            intScoresExam = intExam / Score_High;// intScoreWeightA / 100;
                        }
                        else if (intExam >= Score_High && Score_High > 0)
                        {
                            intScoresExam = 1;
                        }
                        else
                        {
                            intScoresExam = 0;
                        }
                    }
                    //计算每个学员每门课的学分(百分比)
                    //intscoresStuCou = intScoresHours + (intWorkScores + intScoresComment) * intworkTatolWeightA + intScoresExam;
                    intscoresStuCou = intScoresHours * (intTotalTimeWeightA / 100) + ((intWorkScores * (intFinishTimesWeightB / 100)) + (intScoresComment * (workCommentTimesWeightB / 100))) * intworkTatolWeightA + (intScoresExam * (intScoreWeightA / 100));
                    if (intscoresStuCou >= int.Parse(strCourseIDB[1]) && dtCourseInfo.Rows.Count>0)
                    {
                        //确保该课程设置了学分
                        int intCourseScoreA = 0;
                        if (dtCourseInfo.Rows.Count > 0)
                        {
                            if (!string.IsNullOrEmpty(dtCourseInfo.Rows[0]["Score"].ToString()))
                            {
                                intCourseScoreA = int.Parse(dtCourseInfo.Rows[0]["Score"].ToString());
                            }
                        }
                        douScoreP = (intscoresStuCou / 100) * intCourseScoreA;
                    }
                    else
                    {
                        douScoreP=0;
                    }
                    //计算每个学员的总学分
                    intscoresStu = intscoresStu + douScoreP;
                    intscoresStuCou = 0;
                    
                }
                //把每个学生的总分添加到表中
                dtUser.Rows[m]["colScoreStu"] = intscoresStu.ToString("#0.00");
            }
        //排名
        DataView dv = dtUser.DefaultView;
        if (dtUser.Rows.Count > 0)
        {
            dv.Sort = "colScoreStu desc ,UserName asc,Name asc";
            dtUser = dv.ToTable();
            for (int j = 0; j < dtUser.Rows.Count; j++)
            {
                dtUser.Rows[j]["levelStu"] = j+1;
            }
        }
        Session["stuLevel"] = dtUser;
        rptNew.DataSource = dtUser;
        rptNew.DataBind();
    }

    private void BinderPGB(string search)
    {
        if (Session["ClassUserNum"] != null)
        {
            ClassUserNum = Session["ClassUserNum"].ToString();
        }
        
        DataTable dt = obj.Query(search);
        DataTable dtUser = new DataTable();
        dt.Columns.Add("colScoreStu");//学员得分
        dt.Columns.Add("levelStu");//学员名次
        if (Session["stuLevel"]!=null)
        {
            dtUser = (DataTable)Session["stuLevel"];
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                for (int j = 0; j < dtUser.Rows.Count;j++ )
                {
                    if (dtUser.Rows[j]["UserID"].ToString().Equals (dt.Rows[i]["UserID"].ToString()))
                    {
                        dt.Rows[i]["colScoreStu"] = dtUser.Rows[j]["colScoreStu"].ToString();
                        dt.Rows[i]["levelStu"] = dtUser.Rows[j]["levelStu"].ToString();
                    }
                }
            }
        }
        rptNew.DataSource = dt;
        rptNew.DataBind();
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        string search = GetSearch(int.Parse(ViewState["CID"].ToString()));
        BinderPGB(search);
    }
    protected void rptNew_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if (e.CommandName.ToLower() == "sturoleinfo")
        {

            string url = "StuRoleInfo.aspx?StuID=" + e.CommandArgument.ToString() + " &CID=" + ViewState["CID"].ToString();
            Script.RedirectURL(url);

        }
    }
}
